<template>
  <div class="register-container">
    <el-form :model="form" ref="form" class="register-form" @submit.native.prevent="onSubmit">
      <h2 class="title">注册</h2>
      <el-form-item prop="username">
        <el-input v-model="form.username" placeholder="用户名" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="form.password" type="password" placeholder="密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" style="width:100%">注册</el-button>
        <el-link type="primary" @click="$router.push('/login')">已有账号？去登录</el-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import service from '@/utils/request';
export default {
  name: 'Register',
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    async onSubmit() {
      try {
        const res = await service.post('/user/register', this.form);
        if (res.data.code === 200) {
          this.$message.success(res.data.message + '，请登录');
          this.$router.push('/login');
        } else {
          this.$message.error(res.data.message);
        }
      } catch (e) {
        this.$message.error('注册失败');
      }
    }
  }
}
</script>

<style scoped>
.register-container {
  width: 400px;
  margin: 120px auto;
  padding: 40px 30px 30px 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px #ccc;
}
.title {
  text-align: center;
  margin-bottom: 30px;
}
</style> 